package com.server.scheduler;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.server.service.ICourseStudyService;
import com.server.service.IMsgManagementService;
import com.server.service.IUserAssignmentService;
import com.server.service.IVerifyService;

@Component
public class CommonScheduler {
	
	private ExecutorService threadPool = null;
	
	@Autowired
	private IVerifyService verifyService;
	@Autowired
	private IUserAssignmentService userAssignmentService;
	@Autowired
	private ICourseStudyService courseStudyService;
	@Autowired
	private IMsgManagementService managementService;

	public CommonScheduler(){
		threadPool = Executors.newCachedThreadPool(new ThreadFactory() {
			@Override
			public Thread newThread(Runnable r) {
				Thread thread = new Thread(r);
				thread.setDaemon(true);
				return thread;
			}
		});
	}
	
	 /**
	 * 1、用户登录状态查询并记录登出时间
	 * 2、将缓存的课程点击量更新到数据库
	 * @throws InterruptedException
	 * @author ServerZhang
	 * @date 2016年7月13日
	 */
	@Scheduled(cron = "0 0/10 * * * ?")
	public void checkStatus() throws InterruptedException{
		threadPool.execute(new Runnable(){
            @Override 
            public void run() { 
            	verifyService.cleanRegisterCode();
            	courseStudyService.clickRecord();
            } 
        });   
	}
	
	/**
	 * 1、每天重新获取专家、审核人员保存到内存
	 * 目的：保证数据准确性
	 * 2、每天清理一次过期附件
	 * 过期附件：被用户删除超过30天
	 * @throws InterruptedException
	 * @author ServerZhang
	 * @date 2016年7月13日
	 */
	@Scheduled(cron = "0 0 3 * * ?")
	public void attachClean() throws InterruptedException{
		threadPool.execute(new Runnable(){
			@Override 
			public void run() { 
				//userAssignmentService.loadUser();
			} 
		});   
	}
	
	/**
	 * 每隔30分钟将缓存的课程点击量更新到数据库
	 * @throws InterruptedException
	 * @author ServerZhang
	 * @date 2016年8月9日
	 */
	@Scheduled(cron = "0 0/30 * * * ?")
	public void courseClickRecord() throws InterruptedException{
		threadPool.execute(new Runnable(){
			@Override 
			public void run() { 
				//courseStudyService.clickRecord();
			} 
		});   
	}
	
	/**
	 * 每隔3分钟查询一次是否有需要推送的消息
	 * @throws InterruptedException
	 * @author ServerZhang
	 * @date 2016年8月9日
	 */
	@Scheduled(cron = "0 0/3 * * * ?")
	public void msgPush() throws InterruptedException{
		threadPool.execute(new Runnable(){
			@Override 
			public void run() {
				managementService.autoPush();
			} 
		});   
	}
}
